package activity.wheelOfFortune;

import activity.CustomActivity;
import coupon.DiscountCoupon;
import coupon.DiscountCouponDetail;
import coupon.DiscountCouponDetailHistory;
import enums.PrizeType;
import enums.ReceiveStatus;
import models.BaseModel;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import models.weixin.WebUser;
import play.Logger;
import play.data.validation.Required;
import play.modules.paginate.JPAExtPaginator;
import product.merchant.ProductSpecMerchant;
import util.common.UStringUtil;
import util.xsql.XsqlBuilder;

import javax.persistence.*;
import java.util.*;

/**
 * Created by LiuBin on 2016/5/13.
 */
@Entity
@Table(name = "prize_items")
public class PrizeItem extends BaseModel {



    //活动
    @ManyToOne
    @JoinColumn(name = "custom_activity_id")
    public CustomActivity customActivity;

    /**
     * 中奖产品
     */
    @ManyToOne
    @JoinColumn(name = "product_spec_merchant_id")
    public ProductSpecMerchant product;


    /**
     * 奖项名称
     */
    @Column(name = "name")
    @Required(message = "奖项名称必填")
    public String name;

    /**
     * 奖品类型
     */
    @Column(name = "prize_type")
    @Enumerated(EnumType.STRING)
    public PrizeType prizeType;

    /**
     * 金额
     */
    @Column(name = "money")
    public Double money = 0D;


    /**
     * 中奖概率
     */
    @Column(name = "prize_probability")
    public Double probability = 0D;

    /**
     * 是否使用最大奖品数量
     */
    @Column(name = "use_quantity")
    public Boolean useQuantity = false;

    /**
     * 最大奖品数量
     */
    @Column(name = "prize_quantity")
    public Integer quantity = 0;

    /**
     * 中奖次数
     */
    @Column(name = "winning_times")
    public Integer winningTimes = 0;

    /**
     * 奖品有效时间 , 天数
     */
    @Column(name = "valid_time")
    public Integer validTime ;

    /**
     * 图片地址
     */
    @Column(name = "image_url")
    public String imageUrl;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 备注
     */
    @Column(name = "remark")
    public String remark;



    // 放大倍数
    private static final int mulriple = 100;

    public PrizeItem() {
    }

    public PrizeItem(Integer prizeId, Double probability, Integer quantity) {
        this.probability = probability;
        this.quantity = quantity;
        this.createAt = new Date();
        this.deleted = DeletedStatus.UN_DELETED;
    }

    /**
     * 分页查询.
     */
    public static JPAExtPaginator<PrizeItem> findByCondition(
            Map<String, Object> conditionMap, String orderByExpress,
            Integer pageNumber, Integer pageSize) {
        StringBuilder xsqlBuilder = new StringBuilder(" deleted = models.constants.DeletedStatus.UN_DELETED ")
                .append("/~ and t.deleted = {deleted} ~/");
        XsqlBuilder.XsqlFilterResult result = new XsqlBuilder().generateHql(xsqlBuilder.toString(), conditionMap);
        Logger.info("PrizeItem.xsql=" + result.getXsql());
        JPAExtPaginator<PrizeItem> prizeItemPage = new JPAExtPaginator<>("PrizeItem t", "t", PrizeItem.class, result.getXsql(), conditionMap)
                .orderBy(orderByExpress);
        prizeItemPage.setPageNumber(pageNumber);
        prizeItemPage.setPageSize(pageSize);
        prizeItemPage.setBoundaryControlsEnabled(false);
        return prizeItemPage;
    }

    public static List<PrizeItem> loadByCustomActivityId(long customActivityId){
        return PrizeItem.find(" customActivity.id = ? and deleted = ? order by id" , customActivityId , DeletedStatus.UN_DELETED).fetch();
    }

    public static Map<String,Object> getLuckNumer(WebUser weixinUser , long activityId) {
        //获取转盘活动下的奖品
        List<PrizeItem> prizeItemList = PrizeItem.loadByCustomActivityId(activityId);
        Map<String,Object> resultMap = new HashMap<String,Object>();
        Map<Long, Integer> idToIndex = new HashMap<>();
        Map<Long, PrizeItem> idToPrize = new HashMap<>();
        List<Long> randomList = new ArrayList<>();
        for (int i = 0; i < prizeItemList.size(); i++) {
            PrizeItem prize = prizeItemList.get(i);
            if (prize.useQuantity == false || (prize.useQuantity == true && (prize.quantity - prize.winningTimes) > 0)) {
                Long prizeId = prize.id;

                idToIndex.put(prizeId, i + 1);
                idToPrize.put(prizeId, prize);
                int probability = (int) (prize.probability * 100);
                for (int j = 0; j < probability; j++) {
                    randomList.add(prizeId);
                }
            }
        }

        //打乱排序

        // 获取1-最大值之间的一个随机数
        if(randomList!= null && randomList.size()>0) {
            Collections.shuffle(randomList);

            int luckyNumber = new Random().nextInt(randomList.size());

            long luckyPrizeId = randomList.get(luckyNumber);

            //更新奖品中奖次数和奖品数量
            PrizeItem prizeItem = idToPrize.get(luckyPrizeId);
            prizeItem.winningTimes = (prizeItem.winningTimes == null ? 0 : prizeItem.winningTimes) + 1;
//        if (prizeItem.useQuantity == true)
//            prizeItem.quantity = prizeItem.quantity == null ? 0 : (prizeItem.quantity - 1);
            prizeItem.save();
            Merchant merchant = prizeItem.customActivity.merchant != null ? prizeItem.customActivity.merchant : null;

            //根据情况保存实物奖品或者优惠券
            if (prizeItem.prizeType == PrizeType.SHIWU) {
                //奖品为实物
                PrizeHistory prizeHistory = new PrizeHistory(weixinUser, "实物:" + prizeItem.name);
                prizeHistory.lastChance = weixinUser.prizechance;
                prizeHistory.merchant = merchant;
                prizeHistory.createAt = new Date();
                prizeHistory.validTime = prizeItem.validTime;
                prizeHistory.save();

                //创建奖品
                UserPrizes userPrize = new UserPrizes();
                userPrize.name = prizeItem.name;
                userPrize.prizeProduct = prizeItem;
                userPrize.weixinUser = weixinUser;
                userPrize.imageUrl = prizeItem.imageUrl;
                userPrize.prizeType = prizeItem.prizeType;
                userPrize.prizeTime = new Date();
                userPrize.createAt = userPrize.prizeTime;
                userPrize.receiveStatus = ReceiveStatus.UNRECEIVE;
                userPrize.deleted = DeletedStatus.UN_DELETED;
                userPrize.validTime = prizeItem.validTime;
                userPrize.merchant = merchant;
                userPrize.save();
            } else if (prizeItem.prizeType == PrizeType.YOUHUIQUAN) {
                //奖品为优惠券
                //创建奖品
                UserPrizes userPrize = new UserPrizes();
                userPrize.name = prizeItem.name;
                userPrize.weixinUser = weixinUser;
                userPrize.imageUrl = prizeItem.imageUrl;
                userPrize.prizeType = prizeItem.prizeType;
                userPrize.prizeTime = new Date();
                userPrize.createAt = userPrize.prizeTime;
                userPrize.receiveStatus = ReceiveStatus.RECEIVED;
                userPrize.deleted = DeletedStatus.UN_DELETED;
                userPrize.merchant = merchant;
                userPrize.save();

                PrizeHistory prizeHistory = new PrizeHistory(weixinUser, "优惠券:" + prizeItem.name);
                prizeHistory.lastChance = weixinUser.prizechance;
                prizeHistory.merchant = merchant;
                prizeHistory.createAt = new Date();
                prizeHistory.save();

                //检索抽奖专用的优惠券
                DiscountCoupon discountCoupon = DiscountCoupon.findByDiscountCouponId(prizeItem.customActivity.discountCoupon.id);
                System.out.println("discountCoupon:" + discountCoupon + "\n prizeItem:" + prizeItem.customActivity.discountCoupon.id);

                if (discountCoupon != null) {
                    DiscountCouponDetail userCouponDetail = DiscountCouponDetail.findByWebUserAndCoupon(weixinUser, discountCoupon);
                    if (userCouponDetail != null) {
                        userCouponDetail.amount = userCouponDetail.amount + prizeItem.money;
                        userCouponDetail.save();
                    } else {
                        userCouponDetail = new DiscountCouponDetail(weixinUser, discountCoupon, prizeItem.money).save();
                    }

                    new DiscountCouponDetailHistory(userCouponDetail, prizeItem.money, "幸运大转盘抽奖获得优惠券:" + prizeItem.money + "元").save();
                }

//            WeixinUserWallet wallet = WeixinUserWallet.findByWeixinUser(weixinUser);
//            if(wallet == null) {
//                wallet = new WeixinUserWallet(weixinUser , new BigDecimal(prizeItem.money)).save();
//            } else {
//                wallet.amount =  wallet.amount.add(new BigDecimal(prizeItem.money));
//                wallet.save();
//            }
//            new WalletHistory(wallet , new BigDecimal(prizeItem.money) , "幸运大转盘抽奖").save();
            }
            resultMap.put("winningIndex",idToIndex.get(luckyPrizeId));
            resultMap.put("winningPrize",prizeItem.prizeType);
            return resultMap;
        }else{
            resultMap.put("winningIndex",-1);
            return resultMap;
        }
    }

    /**
     * 加载转盘抽奖活动的奖品
     * @param id 转盘活动Id
     * @return
     */
    public static List<PrizeItem> loadPrizeItemList(long id) {
        return PrizeItem.find("customActivity.id=? and customActivity.deletedStatus=? and deleted=?", id, DeletedStatus.UN_DELETED,DeletedStatus.UN_DELETED).fetch();
    }

    //根据ID查询出大转盘活动
    public  static PrizeItem findByPrizeId(long id ){
        return PrizeItem.find("id=? and deleted=?", id, DeletedStatus.UN_DELETED).first();
    }

    /**
     * 删除Item
     */
    public static void deleteItems(Integer[] delItemIdArray) {
        String sql = "update prize_items set deleted = ? where id in (" + UStringUtil.concatStr(",", delItemIdArray) + ")";
        em().createNativeQuery(sql).setParameter(1, DeletedStatus.DELETED.getValue()).executeUpdate();
    }

}
